# server.py文件，记得把那两个生成的.py文件放到同一个目录下哦
import grpc
import time
from concurrent import futures
from python_proto import data_pb2, data_pb2_grpc
import cv2
import base64
import numpy as np
import sys
import threading

class ServerGreeter(data_pb2_grpc.dataServicer):
    ocr_class = 0

    def __init__(self):
        '''初始化OCR识别类'''
        pass

    def serving(self, request, context):
        '''服务类，用来监视及响应客户端'''
        print('revive request image:')
        decode_img = base64.b64decode(request.cmd)  # 先解码
        img = np.fromstring(decode_img, dtype=np.int8)  # 变成一个矩阵
        img_decode = cv2.imdecode(img, cv2.IMREAD_COLOR)  # 再解码成图片

        print('process request image:') # dong something 该处理什么 就处理什么
        # res_img,rec_text = self.ocr_class.run_ocr(rec_img=img_decode) # 算法实现
        # rgb = bgr[..., ::-1] # bgr与rgb互转，Paddleocr在可视化的时候，新建的图是RGB的，但是opencv是BGR的
        res_img = np.ones((49, 102, 3))
        res_img[:, :, 1] = 255;
        bgr_IMG = res_img[..., ::-1]
        cv2.imwrite('./ph.jpg', bgr_IMG)

        print('post res image:')
        img_encode = cv2.imencode('.jpg', bgr_IMG)[1] # 先把图片编码，取第二个参数
        data_encode = np.array(img_encode) # 再把编码后的变成数组
        str_encode = data_encode.tostring() # 再变成字符串
        img_64 = base64.b64encode(str_encode) # 再编成base64发出去。这是必须的
        return data_pb2.data_reply(values=img_64) # 函数返回，就像本地调用一样

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # 最大客户端连接10(max_workers=10)
    data_pb2_grpc.add_dataServicer_to_server(ServerGreeter(), server) # 把我们的类注册到服务去
    server.add_insecure_port('[::]:5001')  # 端口
    server.start()  # 服务启动
    print('XX服务已启动......')

    # 奇葩的start()，自己不会开线程阻塞。如果有其它事干，自己开个线程吧，在多线程中干它
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        server.stop(0)


def main():
    # 开线程干它。我这里就是演示一下
    # t1 = threading.Thread(target=serve)
    # t1.start()
    pass
    serve()

if __name__ == '__main__':
    main()
